import crypto from 'crypto';

function get_req_url(params: any, endpoint: string) {
    params.Signature = escape(params['Signature']);
    const url_strParam = sort_params(params)
    return "https://" + endpoint + "/?" + url_strParam.slice(1);
}

function formatSignString(reqMethod: string, endpoint: string, path: string, strParam: string) {
    let strSign = reqMethod + endpoint + path + "?" + strParam.slice(1);
    return strSign;
}
function sha1(secretKey: string, strsign: string) {
    let signMethodMap = { 'HmacSHA1': "sha1" };
    let hmac = crypto.createHmac(signMethodMap['HmacSHA1'], secretKey || "");
    return hmac.update(Buffer.from(strsign, 'utf8')).digest('base64')
}

function sort_params(params: any) {
    let strParam = "";
    let keys = Object.keys(params);
    keys.sort();

    for (let k in keys) {
        //k = k.replace(/_/g, '.');
        if(params[keys[k]]==null||params[keys[k]]=='')
            continue
        strParam += ("&" + keys[k] + "=" + params[keys[k]]);
    }
    return strParam
}

function main(text: string) {
    // 密钥参数
    const SECRET_ID = "AKIDvgCTVIrBG6hmcDZfW8VcWCdojPp0wd4G"
    const SECRET_KEY = "znNioeHgqkPoytZ0B7pHUSAcpnVyB9sN"

    const endpoint = "tts.tencentcloudapi.com"
    const Region = "ap-chengdu"
    const Version = "2019-08-23"
    const Action = "TextToVoice"
    const Timestamp = Math.round(Date.now() / 1000)
    const nonce = Math.round(Math.random() * 65535)
    const SessionId = Date.now()

    let params = {
        Action: Action,
        Language: "zh-CN",
        SessionId: SessionId,
        Nonce: nonce,
        Region: Region,
        SecretId: SECRET_ID,
        Timestamp: Timestamp,
        Version: Version,
        Signature: '',
        Text: text
    };

    // 1. 对参数排序,并拼接请求字符串
    const strParam = sort_params(params)

    // 2. 拼接签名原文字符串
    const reqMethod = "GET";
    const path = "/";
    const strSign = formatSignString(reqMethod, endpoint, path, strParam)
    console.log("拼接后=="+strSign);
    
    // 3. 生成签名串
    params.Signature = sha1(SECRET_KEY, strSign)

    // 4. 进行url编码并拼接请求url
    const req_url = get_req_url(params, endpoint)
    console.log(req_url)
    return req_url
}
export default main